import os
import socket
import subprocess
import sys
import time

from PyQt6.QtWidgets import QMessageBox, QApplication

from config import get_config
from config import init_config


class JavaUtil(object):
    def __init__(self, config_path):
        if not config_path:
            self.config_path = 'config.ini'
        else:
            print("config_path:", config_path)
            self.config_path = config_path

        init_config(self.config_path)

        self.port = get_config(self.config_path, 'java', 'port')

    def check_port(self):
        """
        Check if the port is in use
        """
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(3)
            result = s.connect_ex(('localhost', int(self.port)))
            if result == 0:
                return True
            else:
                return False

        except Exception as e:
            print(e)
            return False
        finally:
            s.close()

    # def check_process_by_port():
    #     # " 查找进程 "
    #     for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
    #         try:
    #             if check_port(port):
    #                 if 'java' in proc.info['name'] and 'java' in proc.info['cmdline']:
    #                     print( proc.pid, proc.info['name'], proc.info['cmdline'])
    #                     return True
    #                 else:
    #                     return False
    #             else:
    #                 return False
    #         except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
    #             print("Error occurred while checking process:", proc.info['name'])
    #             return False

    def start_java(self):
        """
        Start the java process
        """
        jar_name = get_config(self.config_path, 'java', 'jar_path')
        port = get_config(self.config_path, 'java', 'port')
        java_path = get_config(self.config_path, 'java', 'java_path')
        proname = get_config(self.config_path, 'project', 'project_name')
        db_host = get_config(self.config_path, 'postgres', 'host')
        db_port = get_config(self.config_path, 'postgres', 'port')
        db_name = get_config(self.config_path, 'postgres', 'database')
        args = get_config(self.config_path, 'project', 'project_args')
        env = get_config(self.config_path, 'project', 'project_env')
        redis_port = get_config(self.config_path, 'redis', 'port')
        ##java -jar C:\dbMidder\dbMidder-1.8.0-exec.jar --spring.profiles.active=xuchang --spring.profiles.active=dev --spring.datasource.dynamic.datasource.Manager.url=jdbc:postgresql://100.1.2.207:5432/postgres --spring.redis.port=6379 --server.port=8585 --info.active=xuchang --info.httpMode=http
        # javacmd = java_path +' -jar '+ jar_name +' --spring.profiles.active=' + proname +' --spring.profiles.active=dev --spring.datasource.dynamic.datasource.Manager.url=jdbc:postgresql://' + db_host + ':' + db_port + '/' + db_name +' --spring.redis.port=6379 --server.port=' + port +' --info.active=' + proname +' --info.httpMode=http --spring.profiles.active=' + proname ' --spring.profiles.active=dev --spring.datasource.dynamic.datasource.Manager.url=jdbc:postgresql://' + db_host + ':' + db_port + '/' + db_name +' --spring.redis.port=6379 --server.port=' + port + ' --info.active=' + proname +' --info.httpMode=http'
        javacmd = f"java -jar {jar_name} --spring.profiles.active={proname} --spring.profiles.active={env} --spring.datasource.dynamic.datasource.Manager.url=jdbc:postgresql://{db_host}:{db_port}/{db_name} --spring.redis.port={redis_port} --server.port={port} --info.active={proname} --info.httpMode=http {args}"

        if self.check_port():
            print('Port is in use, please check the port number')
            QMessageBox.warning(None, '错误', f'端口{port}被占用，请检查进程号')
            return False
        else:
            try:
                os.chdir(java_path)
                print(os.path.abspath(os.curdir))
                QMessageBox.information(None, '提示', f'启动Java命令：{javacmd}')
                # jt = subprocess.Popen(["cmd", "/c", f"start", "cmd", "/k", javacmd], shell=True, stdout=subprocess.PIPE,
                #                      stderr=subprocess.PIPE)
                jt = subprocess.Popen(["cmd", "/c", f"start", "cmd", "/k", f"title dbmidder-start.exe &&  {javacmd}"],
                                      creationflags=subprocess.CREATE_NEW_CONSOLE, shell=True, stdout=subprocess.PIPE)
                while jt.poll() is None:
                    if jt.returncode == 0:
                        print('Java process  starting  ....')

                time.sleep(15)
                # for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
                #     if 'java' in proc.info['name'] and 'java' in proc.info['cmdline']:
                #         print(proc.pid, proc.info['name'], proc.info['cmdline'])

                if self.check_port():
                    print('Java process has been started')
                    QMessageBox.information(None, '提示', 'Java进程启动成功')
                    return True
                else:
                    jt.terminate()
                    print('Java process is not running')
                    QMessageBox.warning(None, '错误', 'Java进程未启动，请检查日志')
                    return False
            except Exception as e:
                print(e)
                QMessageBox.warning(None, '错误', f'Java进程未启动：{e}')
                return False

    def stop_java(self):
        """
        Stop the java process
        """
        pid, name, cmdline = self.check_port()
        if pid:
            os.kill(pid, 9)
            print('Java process has been stopped')
        else:
            print('Java process is not running')

    def main(self):
        if self.check_port():
            print('Port is in use, please check the port number')
            process = self.check_port()
            if process:
                print(f'Java process is running with pid ')
            else:
                print(f'端口被占用，请检查进程号: ')
        else:
            print('Starting Java process...')
            self.start_java()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    t = JavaUtil()
    t.main()
    app.exec()
